<?php
import("ORG.Util.QPage");
import("@.Org.Page");
import("ORG.Util.Image");
import("ORG.Util.Function");
import('ORG.Net.UploadFile');
import('ORG.Net.Upload');
import('ORG.Util.Article');

class CourseAction extends CommonAction {
	
	/**
	 * Initialize Function 
	 * @see CommonAction::_initialize()
	 */
	public function _initialize(){
		parent::_initialize();
				
		$param           =    $this->_get('_URL_');
		$controller      =    $param[0];
		$action          =    $param[1];
		
		//language
		$lang            =    L($action);  		
		$manage          =    L('manage');
		
		$this->assign("manage",$manage);
		$this->assign("current",$lang);
		$this->assign("lang",$lang);
	}
	
	/**
	 * course_page
	 * @param cat_id int
	 * @param is_new int
	 * @param is_hot int
	 * @param keyword string
	 * 
	 */
	public  function course(){			
		$sql	=		"
						SELECT baby_course . * , baby_supplier.name supplier_name, baby_course_category.name cat_name
						FROM  `baby_course`
						LEFT JOIN baby_course_category ON baby_course_category.id = baby_course.course_category_id
						LEFT JOIN baby_supplier ON baby_supplier.id = baby_course.supplier_id						
						";
		
		//帅选框
		if(!empty($_GET)){
			//分类id
			$cat_id					= 	intval($this->_get('cat_id'));//intval将字符型转化为整型			
			if(!empty($cat_id)) 
				$con['cat_id']		=	$cat_id;
			//商品上架或下架
			$invalid				=	null;
			if(array_key_exists('invalid',$_GET)){				
				$invalid		= 	$this->_get('invalid');//intval将字符型转化为整型
				if($invalid != 'all'){
					$invalid		=	intval($invalid);
					if(isset($invalid)) $con['invalid']	=	$invalid;
				}
			}
			
			//课堂类型						
			$intro_type	=	$this->_get('intro_type');
			switch ($intro_type){
				case "is_new":
					$con['new']	=	1;
					break;
				case "is_hot":
					$con['hot']	=	1;
					break;
				default:
					break;
			}
			
			//搜索关键字		
			$keyword	=	$this->_get('keyword');
			if(!empty($keyword)) $con['name']	=	$keyword;	
				
			//构造帅选条件
			foreach ($con as $k=>$v){
				$data_type	=	gettype($v);
				
				switch($data_type){
					case 'integer':
						if($k == 'cat_id') 
							$where .=  "  baby_course_category." . 'id' . "=" . $v . " and";
						else 
							$where .=  "  baby_course." . $k . "=" . $v . " and";
						break;
					case 'string':
						$where .=  "  baby_course." . $k . "='" . $v . "' and";
						break;
					default:
						break;
				}				
			}
			
			// 条件
			$where	=	substr($where, 0,strlen($where) - 3);
									
			if(!strlen($where) == 0){
				$sql	.=	" where " . $where;
			}
			
			// 排序
			// 排序:根据某字段进行排序
			$sort	=	$this->_get('sort');
			if(!empty($sort)){
				$sql .= "  order by baby_course." . $sort ;
			}	
			// 帅选上架商品
			//$sql .=	" and baby_course.invalid = 0 ";
		}
		/*else {
			$sql .=	" where baby_course.invalid = 0 ";	
		}*/		
		$param = array(
				'result'=>$sql,				//分页用的数组或sql
				'listvar'=>'courselist',	//分页循环变量
				'listRows'=>10,				//每页记录数
				'parameter'=>'cat_id=' . $cat_id . "&intro_type=" . $intro_type . "&invalid=" . $invalid,//url分页后继续带的参数
				'target'=>'content',	    //ajax更新内容的容器id，不带#
				'pagesId'=>'page',			//分页后页的容器id不带# target和pagesId同时定义才Ajax分页
				'template'=>'Library:course_list',//ajax更新模板
		);
		
		$this->page($param);
		//帅选框
		$CourseCategoryModel	=	M('CourseCategory');
		$course_categoryList	=	$CourseCategoryModel->field("id,name")->select();					
		$this->assign("course_categoryList",$course_categoryList);
		$this->display();
	}
	
	/**
	 +----------------------------------------------------------
	 * 分页函数 支持sql和数据集分页 sql请用 buildSelectSql()函数生成
	 +----------------------------------------------------------
	 * @access public
	 +----------------------------------------------------------
	 * @param array  $result 排好序的数据集或者查询的sql语句
	 * @param int    $totalRows  每页显示记录数 默认21
	 * @param string $listvar    赋给模板遍历的变量名 默认list
	 * @param string $parameter  分页跳转的参数
	 * @param string $target  分页后点链接显示的内容id名
	 * @param string $pagesId  分页后点链接元素外层id名
	 * @param string $template ajaxlist的模板名
	 * @param string $url ajax分页自定义的url
	 +----------------------------------------------------------
	 */
	public function page($param) {
		extract($param);
		//总记录数
		$flag = is_string($result);
		
		$listvar = $listvar ? $listvar : 'list';
		$listRows = $listRows? $listRows : 21;
		if ($flag){
			$totalRows	=	count(M()->query($result));
		}			
		else{
			$totalRows = ($result) ? count($result) : 1;
		}
		//创建分页对象
		if ($target && $pagesId)
			$p = new Page($totalRows, $listRows, $parameter, $url,$target, $pagesId);
		else
			$p = new Page($totalRows, $listRows, $parameter,$url);
		//抽取数据
		if ($flag) {
			$result .= " LIMIT {$p->firstRow},{$p->listRows}";
			$voList = M()->query($result);
		} else {
			$voList = array_slice($result, $p->firstRow, $p->listRows);
		}
		$pages = C('PAGE');//要ajax分页配置PAGE中必须theme带%ajax%，其他字符串替换统一在配置文件中设置，
		
		//可以使用该方法前用C临时改变配置
		foreach ($pages as $key => $value) {
			$p->setConfig($key, $value); // 'theme'=>'%upPage% %linkPage% %downPage% %ajax%'; 要带 %ajax%
		}
		//分页显示
		$page = $p->show();		
		//模板赋值
		$this->assign($listvar, $voList);
		$this->assign("page", $page);
		if ($this->isAjax()) {//判断ajax请求
			layout(false);
			$template = (!$template) ? 'ajaxlist' : $template;
			exit($this->fetch($template));
		}
		return $voList;
	}
	
	/**
	 * page 		添加年龄
	 * time			2013-11-25
	 * @abstract	分类，年龄，提供商都必须是有效的
	 * @param
	 * 
	 */
	public function addcourse(){		
		//课堂分类列表
		$CourseCat          =    new Model('CourseCategory');
		$list      			=    $CourseCat->where('invalid = 0')->order('id asc')->select();
		$list				=	 $this->catsort($list,0,0);
		$courseCatList		=	 array();
		foreach($list as $n=>$v){
			$v['name']    	=    str_repeat("&nbsp;&nbsp;&nbsp;&nbsp;",$v['lev']).$v['name'];
			$courseCatList[]=    $v;
		}		
		//年龄列表
		$Ages               =    new Model('Ages');
		$agesList           =    $Ages->where("invalid = 0")->order('id asc')->select();
		//提供商列表
		$Supplier           =    new Model('Supplier');
		$supplierList       =    $Supplier->where("invalid = 0")->order('id asc')->select();
			
		$this->assign('courseCatList',$courseCatList);
		$this->assign('agesList',$agesList);
		$this->assign('supplierList',$supplierList);
		
		$this->display();
	}	
		
	/**
	 * Page		分类列表
	 * time		2013-11-25
	 * @param
	 * @param
	 * 
	 */
	public function category(){
		$Cat             =     new Model('CourseCategory');
		$datas	         =     $Cat->order("sort asc")->where("name != '音乐馆'")->select();		
		//$datas	         =     $Cat->order("sort asc")->select();		
		
		$datas			 = 	   $this->catsort($datas,0,0);
		$catList = array();
		foreach($datas as $n=>$v){
			$v['name']    =    str_repeat("&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;",$v['lev']).$v['name'];
			$catList[]    =    $v;
		}
		$this->assign('catList',$catList);
		$this->display();
	}
	
	/**
	 +----------------------------------
	 * 年龄列表
	 * Age List
	 +----------------------------------
	 * 
	 */
	public function age(){
		$Ages          =     new Model('Ages');
		$agesList      =     $Ages->order(" sort asc ")->select();
	
		$param = array(
				'result'=>$agesList,		//分页用的数组或sql
				'listvar'=>'agesList',	//分页循环变量
				'listRows'=>10,				//每页记录数
				//'parameter'=>'cat_id=' . $cat_id . "&intro_type=" . $intro_type . "&invalid=" . $invalid,//url分页后继续带的参数
				'target'=>'content',	    //ajax更新内容的容器id，不带#
				'pagesId'=>'page',			//分页后页的容器id不带# target和pagesId同时定义才Ajax分页
				'template'=>'Template:age',//ajax更新模板
		);
		
		extract($param);
		//总记录数
		$flag = is_string($result);
		
		$listvar = $listvar ? $listvar : 'list';
		$listRows = $listRows? $listRows : 21;
		if ($flag){
			$totalRows	=	count(M()->query($result));
		}			
		else{
			$totalRows = ($result) ? count($result) : 1;
		}
		//创建分页对象
		if ($target && $pagesId)
			$p = new Page($totalRows, $listRows, $parameter, $url,$target, $pagesId);
		else
			$p = new Page($totalRows, $listRows, $parameter,$url);
		//抽取数据
		if ($flag) {
			$result .= " LIMIT {$p->firstRow},{$p->listRows}";
			$voList = M()->query($result);
		} else {
			$voList = array_slice($result, $p->firstRow, $p->listRows);
		}
				
		$pages = C('PAGE');//要ajax分页配置PAGE中必须theme带%ajax%，其他字符串替换统一在配置文件中设置，
		
		//可以使用该方法前用C临时改变配置
		foreach ($pages as $key => $value) {
			$p->setConfig($key, $value); // 'theme'=>'%upPage% %linkPage% %downPage% %ajax%'; 要带 %ajax%
		}
		//分页显示
		$page = $p->show();		
		//模板赋值
		$this->assign($listvar, $voList);
		$this->assign("page", $page);
		if ($this->isAjax()) {//判断ajax请求
			layout(false);
			$template = (!$template) ? 'ajaxlist' : $template;
			exit($this->fetch($template));
		}		
		$this->display();
	}
	
	/**
	 * supplier
	 *
	 */
	public function supplier(){
		$SupplierModel          =    new Model('Supplier');	
		$SupplierList			=	 $SupplierModel->select();
		
		$param = array(
				'result'=>$SupplierList,		//分页用的数组或sql
				'listvar'=>'supplierList',	//分页循环变量
				'listRows'=>10,				//每页记录数
				//'parameter'=>'cat_id=' . $cat_id . "&intro_type=" . $intro_type . "&invalid=" . $invalid,//url分页后继续带的参数
				'target'=>'content',	    //ajax更新内容的容器id，不带#
				'pagesId'=>'page',			//分页后页的容器id不带# target和pagesId同时定义才Ajax分页
				'template'=>'Course:supplier',//ajax更新模板
		);
		
		extract($param);
		//总记录数
		$flag = is_string($result);
		
		$listvar = $listvar ? $listvar : 'list';
		$listRows = $listRows? $listRows : 21;
		if ($flag){
			$totalRows	=	count(M()->query($result));
		}			
		else{
			$totalRows = ($result) ? count($result) : 1;
		}
		//创建分页对象
		if ($target && $pagesId)
			$p = new Page($totalRows, $listRows, $parameter, $url,$target, $pagesId);
		else
			$p = new Page($totalRows, $listRows, $parameter,$url);
		//抽取数据
		if ($flag) {
			$result .= " LIMIT {$p->firstRow},{$p->listRows}";
			$voList = M()->query($result);
		} else {
			$voList = array_slice($result, $p->firstRow, $p->listRows);
		}
				
		$pages = C('PAGE');//要ajax分页配置PAGE中必须theme带%ajax%，其他字符串替换统一在配置文件中设置，
		
		//可以使用该方法前用C临时改变配置
		foreach ($pages as $key => $value) {
			$p->setConfig($key, $value); // 'theme'=>'%upPage% %linkPage% %downPage% %ajax%'; 要带 %ajax%
		}
		//分页显示
		$page = $p->show();		
		//模板赋值
		$this->assign($listvar, $voList);
		$this->assign("page", $page);
		if ($this->isAjax()) {//判断ajax请求
			layout(false);
			$template = (!$template) ? 'ajaxlist' : $template;
			exit($this->fetch($template));
		}		
		
		
		
		$this->display();
	}
	
	/**
	 * add_supplier_page
	 *
	 */
	public function addsupplier(){		
		$this->display();
	}
	
	public function updateage(){
		$age_id                =   $this->_get('id');		
		$AgesModel             =    new Model('Ages');
		$ages                  =    $AgesModel->where('id=' . $age_id)->find();		
		$this->assign('ages',$ages);
		$this->display();
	}
	
	
	public function updatesupplier(){		
		$id                 =    $this->_get('id');
		
		$SupplierModel      =    new Model('Supplier');
		$supplier           =    $SupplierModel->where('id=' . $id)->find();
		
		$this->assign('supplier',$supplier);
		$this->display();
	}
		
	/**
	 * addcategory_page
	 * 
	 */
	public function addcategory(){
		// 若传递父分类,则页面默认父分类
		if(!empty($_GET['id'])){
			$this->assign("parent_id",$_GET['id']);
		}
		
		$Cat       =     new Model('CourseCategory');
		$data      =     $Cat->field("id,name,parent_id")->select();
		//Sort By parent_id
		$list      =     $this->catsort($data,0,0);		
		
		$catList = array();
		foreach($list as $n=>$v){
			$v['name']    =    str_repeat("&nbsp;&nbsp;&nbsp;&nbsp;",$v['lev']).$v['name'];
			$catList[]    =    $v;
		}
				
		$this->assign("catList",$catList);			
 		$this->display();
	}
	
	/**
	 * updatecourse_page
	* 
	 */
	public function updatecourse(){		
		//取出课堂分类
		$CourseCat         		 =    new Model('CourseCategory');
		$AgesModel               =    new Model('Ages');
		$SupplierModel           =    new Model('Supplier');
		$C_C_Category	         =    M('CourseCourseCategory');
		
		$list      			=    $CourseCat->where('invalid = 0')->order('id asc')->select();
		$list				=	 $this->catsort($list,0,0);	
		//课程分类
		$courseCatList		=	 array();
		foreach($list as $n=>$v){
			$v['name']    	=    str_repeat("&nbsp;&nbsp;&nbsp;&nbsp;",$v['lev']).$v['name'];
			$courseCatList[]=    $v;
		}		
		//年龄列表
		$Ages               =    new Model('Ages');
		$agesList           =    $Ages->where("invalid = 0")->order('id asc')->select();
		//提供商列表
		$Supplier           =    new Model('Supplier');
		$supplierList       =    $Supplier->where("invalid = 0")->order('id asc')->select();
			
		$this->assign('courseCatList',$courseCatList);
		$this->assign('agesList',$agesList);
		$this->assign('supplierList',$supplierList);
			
		//取出课程的信息
		$CourseModel             =     new Model('Course');
		$course_id               =     $this->_get('id');
		$course                  =     $CourseModel->where('id=' . $course_id)->find();
		
		//取出音频列表
		$audio_list			     = 	   M('Audio')->field("baby_audio.name")
												 ->join("baby_audio_course a1 on a1.audio_id = baby_audio.id")
												 ->where("a1.course_id = $course_id")
												 ->select();
		
		$content				 	=		"";
		foreach ($audio_list as $k => $n){
			$content 	.=		$n['name'] . "<br/>";
		}
		//判断存不存在"#$"分隔符
		$explode_result	 = 		explode("#$", $course['description']);
		if(count($explode_result) > 1){
			$course['description']	 =		$course['description'];
		}
		else if(count($explode_result) == 1){
			$course['description']	 =		$course['description'] . "#$" . $content;
		}
		else{
			$course['description']   = 		$course['description'];
		}

		// 拓展分类
		$other_cat_list				 =		$C_C_Category->field('a1.name,a1.id')
														 ->join("baby_course_category a1 on a1.id = baby_course_course_category.course_category_id")
														 ->where("baby_course_course_category.course_id = $course_id")
														 ->select();
		$OtherCatList				 =		array();
		// 构造拓展分类数组
		foreach($other_cat_list as $k => $other_cat){
			$OtherCatList[$k]['selected']	=	$other_cat;
			$OtherCatList[$k]['cat_list']	=	$courseCatList;
		}
		
		$this->assign('OtherCatList',$OtherCatList); /* 拓展分类 */
		$this->assign('course',$course);
		$this->display();
	}
	
	/**
	 * Category Sort
	 * @param unknown $arr
	 * @param number $parent_id
	 * @param number $lev
	 * @return multitype:number
	 */
	public function catsort($arr,$parent_id = 0,$lev = 1){
		static $list = array();
		foreach ($arr as $v){
			if($v['parent_id'] == $parent_id){
				$v['lev']  = $lev;
				$list[]    = $v;
				$this->catsort($arr,$v['id'],$lev +1);
			}
		}
		return $list;
	}
		
	public function brand(){
		$this->display();
	}
	

	/**
	 * Solve adding course
	 */
	public function addCourseOk(){
		//上传文件		
		$Upload                 =    new UploadFile();
		$Upload->maxSize        =    5000000; //大小为5M
		$Upload->allowExts      =    array('jpg', 'gif', 'png', 'jpeg');
		$ymd                    =    date('Ymd');
		$Upload->savePath       =    './Public/Upload/images/' . $ymd . '/'; //按日期目录上传文件
		$Upload->thumb          =    true;
		$Upload->thumbMaxWidth  =    '225';
		$Upload->thumbMaxHeight =    '125';
		
		$datas                  =    array();
		//判断文件
		if($Upload->upload()){
			$fileInfoList       =    $Upload->getUploadFileInfo();			
			foreach($fileInfoList as $k=>$v){
				switch($k){
					case 0:
						$datas ['original_img']    =    $ymd . '/' . $fileInfoList[$k]['savename'];
						$datas ['thum_img']        =    $ymd . '/thumb_' . $fileInfoList[$k]['savename'];
					break;
					case 1:
						$datas ['other_img']       =     $ymd . '/' . $fileInfoList[$k]['savename'];
					break;
				}
			}			
		}
		
		$datas       			=     array_merge($_POST,$datas);
		$datas['description']   =     stripslashes ($datas['description']);
		$datas['ctime']   		=     time();//添加时间
		//将数据保存数据表
				
		$Course      	=     new Model('Course');
		$C_C_Category	=	   M('CourseCourseCategory');
		$id          	=     $Course->add($datas);
		
		// 主分类id
		$course_category_id		=	empty($_POST['course_category_id']) ? null : $_POST['course_category_id'];		
		// 拓展分类 [多个],去掉重复的
		$other_cat_list			=	array_unique($_POST['other_cat_id']);
		// 查找主分类并注销,并去掉重复的分类
		if($course_category_id != null)
			unset($other_cat_list[array_search($course_category_id, $other_cat_list)]);	
		
		// 拓展分类处理
		if($id){
			$this->handle_other_cat($id, $other_cat_list);
		}
		
		$url         =     U('Course/course');
		
		if($id){
			$this->success("该操作成功",$url);
		}	
		else{
			$this->error('该操作失败',$url);
		}		
	}
	
	/**
	 * 拓展分类的处理
	 * time	2013-12-06
	 * @param	good_id		int
	 * @param 	cat_list	array
	 * 
	 */
	public function handle_other_cat($course_id,$other_cat_list = array()){
		
		$C_C_Category	=	M('CourseCourseCategory');
		$datas			=	array();
		$insert_result	=	array();
		
		if($course_id && !empty($other_cat_list)){
			// 删除当前课堂所有的拓展分类
			$C_C_Category->where("course_id = $course_id")->delete();
			// 循环添加新的拓展分类		
			foreach($other_cat_list as $v){
				$datas['course_id']				=	$course_id;
				$datas['course_category_id']	=	$v;
				$datas['ctime']					=	time();
				$insert_result 					=	$C_C_Category->add($datas);
			}
			// 判断有没有插入成功
			return in_array(true, $insert_result);
		}
	}
	
	/**
	+----------------------------------------------------------
	* 兼容课程带有歌词,把课程跟文章联系在一起
	+----------------------------------------------------------
	*/
	public function updatecourseOk(){
				
		$Upload                 =    new UploadFile();
		$Upload->maxSize        =    5000000; //大小为5M
		$Upload->allowExts      =    array('jpg', 'gif', 'png', 'jpeg');
		$ymd                    =    date('Ymd');
		$Upload->savePath       =    './Public/Upload/images/' . $ymd . '/'; /* 按日期目录上传文件 */
		$Upload->thumb          =    true;
		$Upload->thumbMaxWidth  =    '225';
		$Upload->thumbMaxHeight =    '125';
		
		$datas                  =    array();
		//判断文件
		if($Upload->upload()){
			$fileInfoList       =    $Upload->getUploadFileInfo();	
			
			foreach($fileInfoList as $k=>$v){
				$key            =    $fileInfoList[$k]['key'];
				switch($key){
					case 'original_img':
						$datas ['original_img']    =    $ymd . '/' . $fileInfoList[$k]['savename'];
						$datas ['thum_img']        =    $ymd . '/thumb_' . $fileInfoList[$k]['savename'];
					break;
					case 'other_img':
						$datas ['other_img']       =     $ymd . '/' . $fileInfoList[$k]['savename'];
					break;
				}
			}			
		}
		
		//取出post的参数
		$course_id          =      $this->_post('id');
		
		$CourseModel        =      new Model('Course');		
		$fields             =      implode(",",array_keys($datas));
		$img_datas          =      $CourseModel->field($fields)->where('id=' . $course_id)->find();
		
		
		foreach($img_datas as $k){
			$filePath       =     "./Public/Upload/images/" . $img_datas[$k];
			if(file_exists($filePath)) unlink($filePath);
		}
				
		$datas              =     array_merge($_POST,$datas);
		$datas['ctime']		=	  time();
		unset($datas['id']);
				
		$result             =     $CourseModel->where('id=' . $course_id)->save($datas);
		$url                =     U('Course/course');
		
		// 拓展分类入库
		$course_category_id		=	empty($_POST['course_category_id']) ? null : $_POST['course_category_id']; /* 主分类id */ 		
		$other_cat_list			=	array_unique($_POST['other_cat_id']);		
		if($course_category_id != null){
			if(in_array($course_category_id, $other_cat_list)){				
				unset($other_cat_list[array_search($course_category_id, $other_cat_list)]);
			}
		}
				
		$handle_result		=	$this->handle_other_cat($course_id,$other_cat_list); /* 入库结果  */ 
		
		if($result || $handle_result){
			$this->success('修改成功',$url);
		}
		else{
			$this->error('修改失败',$url);
		}	
	}
	
	/**
	 * Update Ages
	 *
	 */
	public function updateageOk(){
		$AgesModel         =   new Model('Ages');
		$datas             =   $AgesModel->create();
		$age_id            =   $datas['id'];

		unset($datas['id']);
		$result            =   $AgesModel->where('id=' . $age_id)->save($datas);
		$url               =   U('Course/age');
		if($result){
			$this->success('该操作成功',$url);
		}	
		else{
			$this->error('该操作失败',$url);
		}
		
	}
	
	/**
	 * update Supplier 
	 *
	 */
	public function updatesupplierOk(){
		//get params	
		$id                     =    $this->_post('id');
		//上传新的图片
		$Upload                 =    new UploadFile();
		$Upload->maxSize        =    5000000; //大小为5M
		$Upload->allowExts      =    array('jpg', 'gif', 'png', 'jpeg');
		$ymd                    =    date('Ymd');
		$Upload->savePath       =    './Public/Upload/images/' . $ymd . '/'; //按日期目录上传文件
		
		$datas                  =    array();
		//判断文件
		if($Upload->upload()){
			$fileInfoList             =    $Upload->getUploadFileInfo();	
			$datas['original_img']    =    $ymd . '/' . $fileInfoList[0]['savename'];
		}
		
		$SupplierModel          =    new Model('Supplier');
		
		if(!empty($datas['original_img'])){
			$field                  =    implode(',',array_keys($datas));			
			$img_data               =    $SupplierModel->field($field)->where('id=' . $id)->find();
			
			$filePath           =    './Public/Upload/images/' . $img_data['original_img'];
			if(file_exists($filePath))
				unlink($filePath);
		}
		
		$datas                  =     array_merge($_POST,$datas);
		
		$result                 =     $SupplierModel->save($datas);
		$url                    =     U('Course/supplier');
		if($result){
			$this->success('该操作成功',$url);
		}
		else{
			$this->error('该操作失败',$url);
		}
		
	}	
	
	/**
	 * add mp3 files 
	 * @Time:2013-09-21
	 * @Author:liuricheng
	 *
	 */
	public function addmp3(){
		//get the id
		$course_id      =    $this->_get('id');
		$con            =    "id=" . $course_id;
		$AudioModel     =    new Model('Audio');
		$audioList      =    $AudioModel->field('baby_audio.*, baby_audio_course.course_id, baby_audio_course.sort')
										->join('right join  baby_audio_course  on baby_audio_course.audio_id=baby_audio.id')
										->where('baby_audio_course.course_id=' . $course_id)
										->select();		
		
		foreach($audioList as $k=>$v){
			$audio_url                    =   $audioList[$k]['audio_url']; 
			$stringArr_1                  =   explode("/",$audio_url);
			$audioList[$k]['audio_url']   =   $stringArr_1[1];
			$lyric_url                    =   $audioList[$k]['lyric_url']; 
			$stringArr_2                  =   explode("/",$lyric_url);
			$audioList[$k]['lyric_url']   =   $stringArr_2[1];			
		}
		
		$this->assign("audiolist",$audioList);
		$this->assign("audioCount",count($audioList));
		$this->assign("id",$course_id);
		$this->display();
		
	}
	
			
	/**
	 * delete mp3
	 */
	public function delAudio(){
		$Audio        =    new Model('Audio');
		$id           =    $_POST['audio_id'];
		$con          =    "audio_id=".$id;
	
		$result       =    $Audio->where($con)->delete();
		if($result){
			$this->ajaxReturn($result,"删除成功",1);
		}else {
			$this->ajaxReturn($result,"删除失败",0);
		}
	}
	
	
	
	/**
	 * add mp3 files ok : [修正版]
	 * @Author:liuricheng
	 *
	 */
	public function addmp3Ok(){		
		$course_id        =     $_POST['id'];
		//存放mp3目录
		$upload           =     new Upload();
		$upload->dir      =     './Public/Upload/music/';
		$folder           =     $upload->createYmdDir();//时间目录		
		//when course_id equal to ""
		if($course_id == "") {
			$this->success("添加失败",U("Course/course"));
			return;
		}		
		unset($_POST['id']);
		$datas         =     $_POST;
	
		$audioList      =    array();
		$sortSector     =    array(); 
		
		foreach ($datas as $k => $data){
			foreach($data as $n=>$v){
				$audioList[$n]['name']           =     $datas[$k][$n];
				$audioList[$n]['audio_url']      =     $folder . "/" . $upload->name() . ".mp3"; //音频的名字
				$audioList[$n]['lyric_url']      =     'lyrics' . "/" . $upload->name() . ".txt"; //音频的名字
				$audioList[$n]['createdtime']    =     time();
				$sortSector[$n]                  =     $datas['sort'][$n];
			}
			break;
		}
		//foreach to insert data into database
		$idArr         =     array();
		$url           =     U('Course/addmp3?id=' . $course_id);
		
		//实例化模型
		$AudioModel            =     new Model('Audio');
		$AudioCourseModel      =     new Model('AudioCourse');
		
		$audio_course_list    =   array();
		$resultArr            =   null;
		//foreach store into audio_table
		foreach($audioList as $n=>$e){
			$audio_id   =     $AudioModel->add($e);
			if($audio_id){
				//构建数组		
				$audio_course_list['course_id']   =   $course_id;
				$audio_course_list['audio_id']    =   $audio_id;
				$audio_course_list['sort']        =   $sortSector[$n];
				$audio_course_list['ctime']       =   time();
				$audio_course_list['invalid']     =   1;				
				$resultArr                        =   $AudioCourseModel->add($audio_course_list);
			}
		}
		
		if($resultArr && !empty($resultArr)){
			$this->success("添加成功",$url);
		}else {
			$this->error("添加失败",$url);
		}
		
	}
	
	/**
	 * 把MP3列表生成excel列表
	 *
	 */
	public function createMp3Excel(){
		//获取相应的参数
		$course_id           =   $this->_get('course_id');
		$Model               =   new Model();
		$audioList           =   $Model->query(
										"
										select a3.name course_name, a1.id, a1.name, a1.audio_url, a1.lyric_url, a2.sort
										from  baby_audio a1
										right join baby_audio_course a2 on a2.audio_id=a1.id
										right join baby_course a3 on a3.id=a2.course_id
										where a2.course_id=$course_id
										order by a2.sort asc
										"
								 );
		//分离url中的文件夹和文件名
		foreach($audioList as $k =>$v){
			$audio_url                    =   $audioList[$k]['audio_url']; 
			$stringArr_1                  =   explode("/",$audio_url);
			$audioList[$k]['audio_url']   =   $stringArr_1[1];
			$lyric_url                    =   $audioList[$k]['lyric_url']; 
			$stringArr_2                  =   explode("/",$lyric_url);
		
			$audioList[$k]['mp3_folder']  =   $stringArr_1[0];
			$audioList[$k]['audio_url']   =   $stringArr_1[1];			
			
			$audioList[$k]['lyric_url']   =   $stringArr_2[1];

		}
		//
		//t($audioList);
		include  "./ThinkPHP/Spreadsheet/Writer.php";
		$workbook       =     new Spreadsheet_Excel_Writer();  
		// 生成 Excel  
		$filename       =     $audioList[0]['course_name'] . '---' .date('YmdHis').'.xls'; 
		
		$workbook->setVersion(8);  
		$workbook->setBIFF8InputEncoding('UTF-8'); 
		$worksheet      =     &$workbook->addWorksheet("Sheet-1");
		$data[]         =     array('所属课程','音频id','音频名称','音频文件名/mp3','歌词文件名/txt','排序','音频所属文件夹'); 
		$audioList      =     array_merge($data,$audioList);
		//把数据插入excel中
		$total_row = count($audioList);  
		$total_col = count($audioList[0]);
		$list = array();
		foreach($audioList as $m => $audio){			
			$n  =   0;
			foreach($audio as $k => $v){
				$list[$m][$n] = $v;
				++$n;
			}
		}
		//插入数据
		for ($row = 0; $row < $total_row; $row ++) {  
		   for ($col = 0; $col < $total_col; $col ++) {  
				$worksheet->writeString($row, $col, $list[$row][$col]);//write data into excel
		   }  
		}	
		$workbook->send($filename);//download
		$workbook->close(); 
	}
		
	/**
	 * Solve adding category
	 */
	public function addcatOk(){
		$datas 			=	 $_POST;		
		$CatModel       =    new Model('CourseCategory');
		$id      	    =    $CatModel->add($datas);	

		$url    	    =    U('Course/category');	
		if($id){
			$this->success("操作成功",$url);
		}
		else {
			$this->error("操作失败",$url);
		}
	}
	
	public function addageOk(){
		$Ages            =    new Model('Ages');
		$datas           =    $_POST;
		$id              =    $Ages->add($datas);
		$url             =    U('Course/age');
		if($id){
			$this->success('操作成功',$url);
		}
		else{
			$this->error('操作失败',$url);
		}
	}
	
	public function addsupplierOk(){
		//上传文件
		$Upload                 =    new UploadFile();
		$Upload->maxSize        =    5000000; //大小为5M
		$Upload->allowExts      =    array('jpg', 'gif', 'png', 'jpeg');
		$ymd                    =    date('Ymd');
		$Upload->savePath       =    './Public/Upload/images/' . $ymd . '/'; //按日期目录上传文件
		
		$datas                  =    array();
		//判断文件
		if($Upload->upload()){
			$fileInfoList            =    $Upload->getUploadFileInfo();	
			$datas['original_img']   =    $ymd . '/' . $fileInfoList[0]['savename'];
		}
		else{
			$this->error('该操作失败',U('Course/addsupplier'));
		}
		
		$datas                  =     array_merge($_POST,$datas);		
		$SupplierModel          =     new Model('Supplier');
		
		$id                     =     $SupplierModel->add($datas);
		$url                    =     U('Course/supplier');
		
		if($id){
			$this->success('该操作成功',$url);
		}
		else{
			$this->error('该操作失败',$url);
		}
	}
	
	
	/**
	 * Add  Tag
	 */
	public function addtagOk(){
		$Tag        =    new Model('Tag');
		$Tag->create();
		$id         =    $Tag->add();
		$url        =    U("Course/tag");
	
		if($id){
			$this->success("添加成功",$url);
		}else {
			$url        =    U("Course/addtag");
			$this->error($url,"添加失败",2);
		}
	}
	
	/**
	 * Delete Tag
	 */
	public function deltag(){
		$id         =   $_POST['id'];
		$con        =   "tag_id=" . $id;
		$Tag        =   new Model('Tag');
		$result     =   $Tag->where($con)->delete();
		if($result){
			$this->ajaxReturn(1,"删除成功",1);
		}else{
			$this->ajaxReturn(0,"删除失败",0);
		}
	}
	
	/**	
	 * Update Tag 
	 */
	public function updatetagOk(){		
		$Tag           =    new Model("Tag");
		$datas         =    $_POST;		
		$id            =    $datas['tag_id'];
		unset($datas['tag_id']);
		
		$result        =    $Tag->where("tag_id=" . $id)->save($_POST);
		
		$url           =    U("Course/tag");
		if($result){
			$this->success("修改成功",$url);
		}else{
			$this->error("修改失败",$url);;
		}
	}
	
	/**
	 * 添加课堂音频包
	 * 
	 * 
	 * 
	 * 
	 */
	public function upload_course_zip(){
		
		//t($_FILES);
		
		$upload                 =    new UploadFile();
		$upload->maxSize        =    100 * 1000 * 1000 ;
		$upload->allowExts      =    array('zip','rar','txt');
		$ymd					=	 date('Ymd');//文件夹,有可能有时间偏差[要有个更好的处理方法]
		$upload->savePath       =    './Public/Upload/zip/' . $ymd .  '/';
		
		$datas					=	 array();
		if(!$upload->upload()) {
			//echo $upload->getErrorMsg();			
			$datas['error']	=	$upload->getErrorMsg();
			$this->ajaxReturn(0,$datas,1);
		}else{
			$info            	=    $upload->getUploadFileInfo();				
			$strArray			=	 explode('.', $info[0]['name']);			
			$datas['url']		=	 $ymd . '/' . $info[0]['savename'];//存储文件名			
			$this->ajaxReturn(1,$datas,1);
		}
	}	
	
	/**
	 * delete_course_zip
	 * @abstract 	删除上传的课堂音频包
	 * @param 	url 	string
	 * 
	 */
	public function delete_course_zip(){
		
		$file_name		=	$this->_post('url');
		$course_id		=	$this->_post('course_id');
		
		$file_path		=	'./Public/Upload/zip/' . $file_name;
		
		$result			=	false;
		if(!empty($course_id)){			
			$this->ajaxReturn(1,"删除成功",1);
		}
		else{
			if(file_exists($file_path)){
				unlink($file_path);
			}
			$this->ajaxReturn(1,"删除成功",1);
		}
	}
	
	/**
	 * course_ajax
	 * 
	 * 
	 * 
	 */
	public function ajaxTable(){		
		$Course             =    new Model('Course');
		$act                =    $_POST['action'];
		//处理不同请求
		switch($act){
			case 'add':
				$this->ajaxReturn(1,"添加成功",1);
				break;
			case 'del':
				$id       			=   $_POST['id'];	
				/*$result   			=   $Course->where("id=$id")->delete();
				
				if($result){
					$this->ajaxReturn($result,"操成功",1);
				}else{
					$this->ajaxReturn($result,"操失败",0);
				}*/		
				$this->ajaxReturn(0,"还没实现",0);
				break;
			case 'update':
				//add code here
				break;
			case 'change':
				$field         =    $_POST['field'];
				$value         =    $_POST['val'];
				$id            =    $_POST['id'];	
				$data[$field]  =    $value;			
				//Save Data
				$result        =    $Course->where("id=$id")->save($data);
				
				if($result){
					$this->ajaxReturn($value,"修改成功",1);
				}
				else{
					$this->ajaxReturn(null,"修改失败",0);
				}
				break;
			default:
				//add code
				break;
		}
	}
	/**
	 +-------------------------------------------------
	 * Ajax 操作课程分类
	 * ajax manage category of the course
	 +-------------------------------------------------
	 * 
	 */
	public function ajaxCategory(){
		$CategoryModel      =    new Model('CourseCategory');
		$CourseModel		=	 M("Course");
		$act                =    $_POST['action'];
		
		switch($act){		
			case 'del':
				$id       		=   $_POST['id'];				
				// 判断分类下面有无课程
				$isHavingCourse =	$CourseModel->query("select count(*) as count from baby_course where course_category_id = '{$id}'"); 				
				// 有课程
				if($isHavingCourse[0]['count'] > 0){
					$msg = "该分类有" . $isHavingCourse[0]['count'] . "个课程,不能删除";
					$this->ajaxReturn(0,$msg,0);
				}
				// 无课程,直接删除
				$result   =    $CategoryModel->where("id=$id")->delete();
				
				if($result){
					$this->ajaxReturn($result,"删除成功",1);
				}else{
					$this->ajaxReturn($result,"删除失败",0);
				}
				break;		
			case 'change':
				$field         =    $_POST['field'];
				$value         =    $_POST['val'];
				$id            =    $_POST['id'];	
				$data[$field]  =    $value;			
				//Save Data
				$result        =    $CategoryModel->where("id=$id")->save($data);
				
				if($result){
					$this->ajaxReturn($value,"修改成功",1);
				}
				else{
					$this->ajaxReturn(null,"修改失败",0);
				}
				break;
		}
	}
	
	/**
	 * ajax Course 编辑表单
	 * time		2013-12-12
	 * @param	action string
	 * @param	id 		int 
	 * @param	field	int or string
	 * @param	value	int or string
	 * 
	 */
	public function ajaxCourse(){
		$action		=	$this->_post('action');
		$msg		=	'';
		
		switch($action){
			case 'edit':
				$CourseModel	=	M('Course');
				// get params
				$id				=	$this->_post('id');
				$field			=	$this->_post('field');
				$value			=	$this->_post('value');				
				// update field
				$result			=	$CourseModel->where("id = $id")->setField($field,$value);
								
				if($result){
					$this->ajaxReturn(1,$value,1);
				}
				else{
					$this->ajaxReturn(0,$value,1);
				}
				break;
			case 'cat_select':
				// 分类名称
				$cat_id		=	$_POST['cat_id'];
				$cat_name 	= 	$this->findParentName($cat_id);				
				$this->ajaxReturn(1,$cat_name,1);
				break;
			default:
				break;
		}
		
		//$this->ajaxReturn(1,"789465",2);
	}
	
	/**
	 * 找出父分类全称
	 * 
	 */
	public  function  findParentName($cat_id){
		$CatModel	=	new Model("CourseCategory");
    	$catList	=	$CatModel->field("id,name,parent_id")->select();
    	$catInfo	= 	$CatModel->field("id,name,parent_id")->where("id = '{$cat_id}'")->find();
    	$parent_id	= 	$catInfo['parent_id'];
    	$cat_name	=	$catInfo['name'];
    	// 判断parent_id是否为0
    	if($parent_id == 0){
    		$cat_name = $catInfo ['name'];
    	}
    	else{
	    	while( $parent_id !=0 ){
		        $catInfo 		= 	$CatModel->field("id,name,parent_id")->where("id = '{$parent_id}'")->find();
		        $cat_name		=	$catInfo['name'] . " > " . $cat_name;
		        $parent_id 		= 	$catInfo['parent_id'];
			}
    	}	   		
		return $cat_name;
	}
		
	/**
	 +--------------------------------------------
	 * Ajax 操作年龄
	 * ajax manage age
	 +--------------------------------------------
	 * 
	 */
	public function ajaxAges(){
		$AgesModel         =     new Model('Ages');
		$action            =     $_POST['action'];
		switch($action){
			case 'del':
				$id       =    $_POST['id'];	
				// 判断提供商的是否需要被删除			
				$result   =    $AgesModel->where("id=$id")->delete();				
				//$this->ajaxReturn($result,"功能尚未开放",1);				
				if($result){
					$this->ajaxReturn($result,"删除成功",1);
				}else{
					$this->ajaxReturn($result,"删除失败",0);
				}
				break;
			case 'change':
				$field         =    $_POST['field'];
				$value         =    $_POST['val'];
				$id            =    $_POST['id'];	
				$data[$field]  =    $value;			
				//Save Data
				$result        =    $AgesModel->where("id=$id")->save($data);
				
				if($result){
					$this->ajaxReturn($value,"修改成功",1);
				}
				else{
					$this->ajaxReturn(null,"修改失败",0);
				}
			break;		
		}	
	}
	
	public function ajaxSupplier(){
		$SupplierModel           =    new Model('Supplier');
		$action                  =    $this->_post('action');
		switch($action){
			case 'del':
				$id       =    $_POST['id'];	
				// 判断提供商的是否需要被删除			
				$result   =    $SupplierModel->where("id=$id")->delete();				
				//$this->ajaxReturn($result,"功能尚未开放",1);				
				if($result){
					$this->ajaxReturn($result,"删除成功",1);
				}else{
					$this->ajaxReturn($result,"删除失败",0);
				}
				break;	
			break;
			case 'change':
				$field         =    $_POST['field'];
				$value         =    $_POST['val'];
				$id            =    $_POST['id'];	
				$data[$field]  =    $value;	
				$result        =    $SupplierModel->where("id=$id")->save($data);
				if($result)
					$this->ajaxReturn($value,"修改成功",1);
				else
					$this->ajaxReturn(null,"修改失败",0);
			break;
		}
		
	}
	
	
	//Ajax_Tag
	public function ajaxTag(){
		$Course             =    new Model('Tag');
		$act                =    $_POST['action'];
		
		switch($act){
			case 'del':
				$id       =    $_POST['id'];
				$result   =    $Course->where("tag_id=$id")->delete();
	
				if($result){
					$this->ajaxReturn($result,"删除成功",1);
				}else{
					$this->ajaxReturn($result,"删除失败",0);
				}
				break;
		}
	}
	
	

	/**
	 * 配置文件
	 * @time	2013-11-15 23:49
	 * @param
	 * @param
	 *
	 */
	public function create_setting_file(){
	
		$id			=	$this->_get('id');
	
		$Course		=	M('Course');
	
		$courseInfo	=	$Course->field("a1.name pageType, baby_course.id pageId, baby_course.name pageName")
								->join("baby_course_category a1 on a1.id = baby_course.course_category_id")
								->where("baby_course.id=$id")->find();
				
		//t($courseInfo);
		//生成文件
		$file_dir 	= 	"./Public/";
		$name 		= 	"notice.properties";
	
		foreach($courseInfo as $k =>$v){
			$string	.=	$k . "=". $v . "\r\n";
		}
		//写入内容
		file_put_contents($file_dir . $name, $string);
	
		$file 		=	fopen($file_dir.$name,"r");
	
		Header("Content-type: application/octet-stream");
		Header("Accept-Ranges: bytes");
		Header("Accept-Length: ".filesize($file_dir . $name));
		Header("Content-Disposition: attachment; filename=".$name);
		echo fread($file, filesize($file_dir.$name));
		fclose($file);
	
	}

	/**
	 * 修改课堂分类
	 * time		201-12-2 22:24
	 * @param
	 * 
	 */
	public function mod_category(){
		$id			=	$this->_get('id');
		$catModel	=	new Model("CourseCategory");		
		$catInfo	=	$catModel->where("id = $id")->find();	
		// 所有分类
		$datas      =     $catModel->field("id,name,parent_id")->select();
		// Sort By parent_id
		$datas      =     $this->catsort($datas,0,1);				
		$catList   = 	 array();
		foreach($datas as $n=>$v){
			$v['name']    =    str_repeat("&nbsp;&nbsp;&nbsp;&nbsp;",$v['lev']).$v['name'];
			$catList[]    =    $v;
		}
		
		$this->assign("catInfo",$catInfo);
		$this->assign("catList",$catList);
		$this->display();
	}
	
	/**
	 * 处理修改课堂分类
	 * time		2013-12-02 22:32
	 * @param
	 * 
	 */
	public function mod_category_ok(){	
		$datas		=	$_POST;
		$id			=	$datas['id'];
		unset($datas['id']);
		
		$result		=	M('CourseCategory')->where("id = $id")->save($datas);		
		if($result){
			$this->success("操作成功",U('Course/category'));
			//$this->redirect("course/category","操作成功");
		}
		else{
			$this->success("操作失败",U('Course/category'));
		}
	}
}